package com.atsmart.app.receiver;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.CellLocation;
import android.util.Log;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.model.CheckDurationInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.PositionInfo;
import com.atsmart.app.model.PositionShutDownInfo;
import com.atsmart.app.model.PositonsInfo;
import com.atsmart.app.service.backService;
import com.atsmart.app.sql.ShutDownSqlHelper;
import com.atsmart.app.utils.LocationUtils;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.atsmart.log.UserLog;
//import com.atsmart.log.UserLog;
import com.baidu.location.LocationClient;
import com.google.json.Gson;

/**
 * @ClassName: SendReceiver
 * @Description:
 * @author zhao
 * @date 2012-5-12 上午11:13:01
 */
public class SendReceiver extends BroadcastReceiver {
	public long stime = 0;

	@Override
	public void onReceive(final Context context, Intent intent) {
//		Log.e("SendReceiver", "/sendReceiver is start");
		final String date = StringUtil.millToDate(BizApp.getInstance().getSendtime());
		
		try {
			new Thread() {
				public void run() {
					boolean ff = System.currentTimeMillis() > (BizApp
							.getInstance().getLocTime() + 70000);
					if (BizApp.getInstance().isNetworkAvailable()
							|| BizApp.getInstance().isWiFiActive()) {
						if (BizApp.getInstance().getCurrentLocation() == null
								|| BizApp.getInstance().getLat() < 0.0001
								|| BizApp.getInstance().getLon() < 0.0001 || ff) {
							try{
								BizApp.getInstance().getmLocationClient().start();
							}catch (Exception e) {
							}
							try {
								sleep(7000);
								int i = 0;
								while (!BizApp.getInstance().isLocation
										&& i < 11) {
									sleep(4000);
									i++;
								}

								if (BizApp.getInstance().isLocation) {
									ff = false;
									BizApp.getInstance().isLocation = false;
								}

								BizApp.getInstance().getmLocationClient()
										.stop();
							} catch (InterruptedException e) {
								//e.printStackTrace();
							}

						}
					}
					
					if (StringUtil.isEmptyOrNull(PrefsUtils.getResult())) {
//						sendloc(ff, date);
						if(PrefsUtils.getLastTime() == null || StringUtil.isEmptyOrNull(PrefsUtils.getLastTime())){
							PrefsUtils.setLastTime(date);
							sendloc(ff, date);
						}else{
//							-------------------("TAG", "当前巡检时间： = " + date + " ,转换后： = " + StringUtil.FormDateToTime(date));
//							Log.e("TAG", "上次巡检时间： = " + PrefsUtils.getLastTime() + " , 转换后： = " + StringUtil.FormDateToTime(PrefsUtils.getLastTime()));
							if(!date.equals(PrefsUtils.getLastTime())){
								if(BizApp.isWrite){
									UserLog.getInstance().writeApkInfo("开始巡检： = " + StringUtil.getCurrentTime());
								}
								sendloc(ff, date);
								PrefsUtils.setLastTime(date);
							}
						}
					}
				}
			}.start();
		} catch (Exception e) {
		}
	}

	public void sendloc(boolean ff, String date) {
		try {
			PositionInfo position = new PositionInfo();

			Gson gson = new Gson();
			CommonBody body = new CommonBody();
			body.setCommand(2);
			body.setImsi(BizApp.getInstance().getIMSI());
			body.setVersion(BizApp.getInstance()
					.getString(R.string.app_version));
			PositonsInfo positions = new PositonsInfo();
			positions.positions = new ArrayList<PositionInfo>();

			position.date = date;
			Double lat_now = null;
			Double lon_now = null;
			if (BizApp.getInstance().isWiFiActive()
					|| BizApp.getInstance().isNetworkAvailable()) {
				lat_now = BizApp.getInstance().getLat();
				lon_now = BizApp.getInstance().getLon();
				position.lat = lat_now;
				position.lon = lon_now;
			} else {
				position.lat = 0.0;
				position.lon = 0.0;
			}
			position.address = "";

			position.locationMsg = LocationUtils.getInstance().getLocationMsg();
//			Log.e("cellid: = ", "cellid： = " +  LocationUtils.getInstance().getLocationMsg());
			position.msgType = 2;// 巡检中

			if (BizApp.getInstance().start) {
				position.msgType = 1;// 巡检开始
			}
			if (BizApp.getInstance().end) {
				position.msgType = 3;// 巡检结束
			}
			BizApp.getInstance().start = false;
			BizApp.getInstance().end = false;
			position.type = 1;// 高精度gps

			positions.positions.add(position);
			if(BizApp.isWrite){
				Log.e("TAG", "当前时间： = " + position.date);
			}
			try{
			if(PrefsUtils.getLastLocData() == null || StringUtil.isEmptyOrNull(PrefsUtils.getLastLocData())){
				PrefsUtils.setLastLocData(position.date);
			}else{
				if((StringUtil.dataToLong(position.date) -  (StringUtil.dataToLong(PrefsUtils.getLastLocData()))) < 50000){
					if (BizApp.isWrite) {
						UserLog.getInstance().writeUnIntent("时间差小于50秒");
					}
//					Log.e("TAG", "时间差小于50秒");
					return;
				}
			}
			if (BizApp.isWrite) {
				UserLog.getInstance().writeUnIntent("时间差  当前时间-上次时间： = "+(StringUtil.dataToLong(position.date) -  (StringUtil.dataToLong(PrefsUtils.getLastLocData()))));
			}
//			Log.e("TAG", "时间差  当前时间-上次时间： = "+(StringUtil.dataToLong(position.date) -  (StringUtil.dataToLong(PrefsUtils.getLastLocData()))));
			PrefsUtils.setLastLocData(position.date);
			}catch (Exception e) {
			}
//			Log.e("巡检内容", gson.toJson(positions));

			ShutDownSqlHelper psql = new ShutDownSqlHelper();
			psql.open(BizApp.getInstance().getSqlHelper());
			// 无网络保存本地，待有网络时上传汇报,若返回定位地址不实时则退出。
			if ((!BizApp.getInstance().isNetworkAvailable() && !BizApp
					.getInstance().isWiFiActive())
					|| BizApp.getInstance().keeping == false) {
//				for (int i = 0; i < 2; i++) {
					PositionShutDownInfo pinfo = new PositionShutDownInfo();
					if (BizApp.isWrite) {
						UserLog.getInstance().writeUnIntent("无网络写入巡检sql" + gson.toJson(positions));
					}
//					Log.e("无网络写入巡检sql", gson.toJson(positions));
					pinfo.setVer(gson.toJson(body));
					pinfo.setPos(gson.toJson(positions));
					pinfo.setType(3);// 巡检结束保存
					psql.addAttribute(pinfo);
//				}

			} else {// 有网络检测sql中是否有保存内容，有--上传sql内容 无--巡检汇报
					PositionShutDownInfo pinfo = new PositionShutDownInfo();
					try {
						CheckDurationInfo info = ServiceHelper.getInstance()
								.postData(ServiceHost.reportLocationURL(),
										gson.toJson(body), gson.toJson(positions),
										CheckDurationInfo.class);
		
						if (info != null && info.getResult() == 0) {
							PrefsUtils.setLastTime(gson.toJson(position));
							
//							Log.e("巡检成功","巡检成功： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
							if(BizApp.isWrite){
								UserLog.getInstance().writeSucessFile("巡检成功： = " + gson.toJson(positions));
							}
								// 上传成功
						} else {// 上传失败
							if(BizApp.isWrite){
								UserLog.getInstance().writeException("上传失败写入巡检sql" + gson.toJson(positions));
							}
		//						Log.e("上传失败写入巡检sql", gson.toJson(positions));
							pinfo.setVer(gson.toJson(body));
							pinfo.setPos(gson.toJson(positions));
							pinfo.setType(3);// 巡检结束保存
							psql.addAttribute(pinfo);
						}
					} catch (Exception e) {
						if(BizApp.isWrite){
							UserLog.getInstance().writeException("异常写入巡检sql" + gson.toJson(positions));
						}
//						Log.e("巡检异常", "巡检异常： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
						pinfo.setVer(gson.toJson(body));
						pinfo.setPos(gson.toJson(positions));
						pinfo.setType(3);// 巡检结束保存
						psql.addAttribute(pinfo);
							//e.printStackTrace();
					}
			}
		} catch (Exception e) {
		}
	}

	public void saveToSDCard(String filename, String content) throws Exception {
		File file = new File(Environment.getExternalStorageDirectory(),
				filename);
		FileOutputStream outStream = new FileOutputStream(file, true);
		outStream.write(content.getBytes());
		outStream.close();
	}
}